package org.fh.nettyService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.codec.binary.Hex;
import org.fh.HandleData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wwy
 * @Date: 2020/8/28 11:09
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyServerHandler.class);
    public static ApplicationContext applicationContext;
    public HandleData handleData = new HandleData();


    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("Channel active......");
        //channelHandlerContextMaps.put(ctx,null);
    }

    /**
     * 客户端发消息会触发
     *
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //LOGGER.info("服务器收到消息: {}", msg.toString());
            ByteBuf buf = (ByteBuf) msg;
            byte[] receiveMsgBytes = new byte[buf.readableBytes()];
            buf.readBytes(receiveMsgBytes);
            String str = Hex.encodeHexString(receiveMsgBytes);
            LOGGER.info("服务端数据接收{}",str);
            handleData.dispose(ctx,str);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
